/* eslint-disable */
/**
 * @author aaron
 * 线路检测逻辑
 */
import axios from "axios"
import qs from "qs"
import { storage } from "../../utils"
import md5 from "blueimp-md5"
import Fingerprint from "../../vendor/scripts/fingerprint"
import ASConstance from "../base/ASConstance"
import { AsyncStorage } from "react-native"

// const PROJECT_VERSION = require("../../../package.json").version

const timestamp = Date.now() + ""

const signParams = {}
storage.load("h5-token").then(data => {
  signParams["token"] = data
})

storage.load("h5-uid").then(data => {
  if (data) {
    signParams["uid"] = data
  }
})

function urlEncode(param, key?: any, encode?: any) {
  if (param == null) return ""
  var paramStr = ""
  var t = typeof param
  if (t === "string" || t === "number" || t === "boolean") {
    paramStr += "&" + key + "=" + (encode == null || encode ? encodeURIComponent(param) : param)
  } else {
    for (var i in param) {
      var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i)
      paramStr += urlEncode(param[i], k, encode)
    }
  }
  return paramStr
}

signParams["device-id"] = new Fingerprint().get() || "timestamp" + timestamp + Math.random()
signParams["os-type"] = 1
signParams["timestamp"] = timestamp
signParams["version"] = "1.0.2" // 取package.json中的version属性
const urlStr = urlEncode(signParams).substr(1)
signParams["sign"] = md5(urlStr + "global")

const headers = {
  Accept: "application/json, text/plain, */*",
  // token: signParams["token"] || "",
  sign: signParams["sign"],
  // Cookie: "",
  // uid: signParams["uid"] || "",
  version: signParams["version"],
  "device-id": signParams["device-id"],
  "os-type": signParams["os-type"],
  timestamp: signParams["timestamp"]
}

const timeout = 8000
const lines = ["https://www.uubody.com", "https://www.okzpps.com", "https://www.tozuuh.com"]

function processHttpRequest(domain, repo, param) {
  return new Promise((resolve, reject) => {
    axios
      .create({
        baseURL: domain,
        timeout: timeout,
        headers: headers
      })
      .post(repo, qs.stringify(param))
      .then(response => {
        resolve(response)
      })
      .catch(error => {
        return resolve(error)
      })
  })
}

function checkWithoutLocalLineFinish(
  node,
  checkLines,
  childLines,
  succeedCallback,
  failureCallback,
  progressCallback
) {
  progressCallback(node / 3)
  if (node == 3) {
    if (checkLines.length == 0) {
      //都检测失败了，欧吼完蛋
      failureCallback("线路检测失败")
      return
    }
    let host = checkLines[0]
    //保存到本地
    let processData = childLines[0]
    let domains = []
    processData.map(item => {
      let resposeDomain = item.domain
      if (resposeDomain.length != 0 && resposeDomain) {
        domains.push(resposeDomain)
      }
    })
    //保存本地
    AsyncStorage.setItem(ASConstance.LINE_CHECK, JSON.stringify(domains), error => {
      console.log(error)
      succeedCallback(host)
    })
  }
}

function checkWithLocalLineFinish(
  node,
  holyLine,
  checkLines,
  succeedCallback,
  failureCallback,
  progressCallback
) {
  //都走完了，选择第一个
  progressCallback(node / holyLine.length)
  if (node == holyLine.length) {
    if (checkLines.length == 0) {
      //都检测失败了，欧吼完蛋
      failureCallback("线路检测失败")
      return
    }

    let host = checkLines[0]
    //返回出克
    succeedCallback(host)
  }
}

//本地没有线路走这
function doCheckWithoutLocalLine(succeedCallback, failureCallback, progressCallback) {
  let childLines = []
  let checkLines = []
  let node = 0
  lines.map(domain => {
    processHttpRequest(domain, "/api/gl/system/domain/list", "").then(
      res => {
        // @ts-ignore
        let result = res.data
        console.log(result)
        node = node + 1
        try {
          if (result.code == 1 && result.data && result.data.length != 0) {
            //请求到数据，塞入数组当中
            //当前返回的domain
            checkLines.push(domain)
            childLines.push(result.data)
          }
        } catch (e) {
          console.log(e)
        } finally {
          checkWithoutLocalLineFinish(
            node,
            checkLines,
            childLines,
            succeedCallback,
            failureCallback,
            progressCallback
          )
        }
        //checkWithoutLocalLineFinish(node,checkLines,childLines,succeedCallback,failureCallback)

        //都走完了，选择第一个
      },
      error => {
        node = node + 1
        checkWithoutLocalLineFinish(
          node,
          checkLines,
          childLines,
          succeedCallback,
          failureCallback,
          progressCallback
        )
      }
    )
  })
}

//本地有线路走这
function doCheckWithLocalLine(localLines, succeedCallback, failureCallback, progressCallback) {
  let checkLines = []
  let node = 0
  let holyLine = lines.concat(JSON.parse(localLines))
  holyLine.map(domain => {
    processHttpRequest(domain, "/api/gl/system/domain/list", "").then(
      res => {
        // @ts-ignore
        let result = res.data
        console.log(result)
        node = node + 1
        try {
          if (result.code === 1 && result.data) {
            //请求到数据，塞入数组当中
            //当前返回的domain
            checkLines.push(domain)
          }
        } catch (e) {
          console.log(e)
        } finally {
          checkWithLocalLineFinish(
            node,
            holyLine,
            checkLines,
            succeedCallback,
            failureCallback,
            progressCallback
          )
        }
      },
      error => {
        node = node + 1
        checkWithLocalLineFinish(
          node,
          holyLine,
          checkLines,
          succeedCallback,
          failureCallback,
          progressCallback
        )
      }
    )
  })
}

export function doCheck(startCallback, succeedCallback, failureCallback, progressCallback) {
  startCallback()
  AsyncStorage.getItem(ASConstance.LINE_CHECK).then(
    localLines => {
      console.log("localLines:" + localLines)
      if (!localLines) {
        //没有线路
        doCheckWithoutLocalLine(succeedCallback, failureCallback, progressCallback)
      } else {
        doCheckWithLocalLine(localLines, succeedCallback, failureCallback, progressCallback)
      }
    },
    () => {
      console.log("reject")
    }
  )
}
